(function($){
	var options = {
		type:"",//image, video
		image:"image/png,image/jpg,image/gif,image/jpeg,",
		video:"video/mp4,",
		orderBy:"desc",//desc asc 上传顺序
        uploadUrl:"/upload/file",//上传地址
        qnToken:"/upload/token",//请求七牛token
        qn:true,//开启七牛上传
        choose:"none",// check radio
        multiple:true,
        hasText:false,
        success:success,
        data:[],
        width:100,
        height:100,
        isClip:false,
        url:null
    };
    var initUpload=function(obj, opt){
    	
    }
    
    var isChoose = function(id,upload){
    	upload.find(".upload-imgbox").each(function(i, v){
    		var img = $(v);
    		var choose = img.find("input[name='"+id+"Checked']").val();
        	if(choose == 'true'){
        		img.find(".upload-choose").show();
        	} else {
        		img.find(".upload-choose").hide();
        	}
    	});
    	
    }
    
    var addFileInput = function(img){
    	img.find('input[type="hidden"],textarea').each(function(i,v){
    		$(v).attr("name", $(v).attr("data"));
    	});
    	
    }
    
    var addFile = function(id, upload, src, opt, typeReq){
    	if(!opt.multiple){
    		upload.find(".upload-yd").remove();
    	}
    	type = typeReq;
    	var fext  = src.substring(src.length-4, src.length);
    	var videos = opt.video.split(",");
    	$.each(videos, function(i,v){
    		v = v.replace("video/", '');
    		if(v != ''){
    			if("."+v == fext){
    				type = 'video';
        		}
    		}
    	});
    	var images = opt.image.split(",");
    	$.each(images, function(i,v){
    		v = v.replace("image/", '');
    		if(v != ''){
    			if("."+v == fext){
    				type = 'image';
        		}
    		}
    	});
    	var src2 = src + '';
    	var video = '';
    	if(type == 'video'){
    		video = '<div class="upload-video-box"></div><div class="upload-video"></div>';
    		src2 = src2 + '?vframe/jpg/offset/2/w';
    		if(typeReq != null){
    			src2 = '';
    		}
		}
    	var img = $('<div class="upload-yd">'+
	    		'<div class="upload-imgbox" style="width:'+opt.width+'px;height:'+opt.height+'px">'+
	    		video+
    			'<span class="upload-close" style="margin-left:'+(opt.width-21)+'px">×</span>'+
    			'<div class="upload-choose" style="width:'+opt.width+'px;margin-top:'+(opt.height-22)+'px">'+
    				'已选'+
    			'</div>'+
    			'<img alt="" style="width:'+opt.width+'px;height:'+opt.height+'px" draggable="true" src="'+src2+'" class="upload-img"/>'+
    			'<input type="hidden" data="'+id+'"/>'+
    			'<input type="hidden" data="'+id+'Type" value="'+type+'"/>'+
    			'<input type="hidden" data="'+id+'Checked" value="false"/>'+
    		'</div>'+
    		'<div class="upload-info" style="height:'+opt.height+'px;"><textarea data="'+id+'Text" placeholder="请填写信息" class="upload-textaea"></textarea></div>'+
		'</div>');
    	
    	if(!opt.hasText){
    		img.find(".upload-info").hide();
    	}
    	
    	uploadYd(upload, img);
    	
    	img.find(".upload-close").click(function(){
    		img.remove();
    		upload.find(".upload-add").show();
    	});
    	
    	if(opt.choose == 'check' || opt.choose == 'radio'){
	    	img.find(".upload-imgbox").click(function(){
	    		var choose = $(this).find("input[name='"+id+"Checked']").val();
	    		if(choose == 'false'){
	    			if(opt.choose == 'radio'){
	    				upload.find("input[name='"+id+"Checked']").val('false');
	    			}
	    			$(this).find("input[name='"+id+"Checked']").val('true');
	    		} else if(choose == 'true' && opt.choose == 'check'){
	    			$(this).find("input[name='"+id+"Checked']").val('false');
	    		}
	    		isChoose(id, upload);
	    	});
	    	isChoose(id, img);
    	}
    	
    	if(opt.orderBy == 'asc' || typeReq == null){
    		upload.find(".upload-add").before(img);
    	} else {
    		upload.prepend(img);
    	}
    	return img;
    }
    
    var selectImg;
    var uploadYd = function(upload, img){
    	var isDialogTitle=false;
    	img.find(".upload-imgbox").on({
    		mousedown: function(e){
    			e.preventDefault();
	            var el=$(this).parent();
	            el.attr("style", 'z-index: 2;');
	            var os = el.offset(); dx = e.pageX-os.left, dy = e.pageY-os.top;
	            $(document).on('mousemove.drag', function(e2){ 
	            	upload.find(".upload-yd").each(function(i,v){
	            		var offLeftStart = $(v).offset().left;
	            		var offLeft = offLeftStart+50;
	            		var offLeftEnd = offLeftStart+100;
	            		
	            		var offTopStart = $(v).offset().top;
	            		var offTopEnd = offTopStart+100;
	            		if(e2.pageY >=offTopStart &&  e2.pageY <=offTopEnd){
	            			if(e2.pageX >= offLeftStart && e2.pageX <= offLeft){
		            			$(v).before(el)
		            		} else if(e2.pageX <= offLeftEnd && e2.pageX >= offLeft){
		            			$(v).after(el)
		            		}
	            		}
	            		
	            	});
	            	el.offset({top: e2.pageY-dy, left: e2.pageX-dx}); 
	            	isDialogTitle = true;
	            	selectImg = el;
	            });
    		},
    		mouseup: function(e){ 
    			var el=$(this).parent();
    			el.attr("style", '');
    			$(document).off('mousemove.drag');
    			isDialogTitle = false;
    			selectImg = null;
    		}
    	});
    }
    var putb64 =function(pic, size, fileName, success){
    	var name = window.btoa(fileName);
    	pic = pic.split("base64,")[1];
        var url = "http://upload.qiniu.com/putb64/"+size+"/key/"+name; //非华东空间需要根据注意事项 1 修改上传域名
        var xhr = new XMLHttpRequest();
        
        var qiniuUrl = "";
        xhr.onreadystatechange=function(){
          if (xhr.readyState==4){
        	  success(qiniuUrl+fileName);
          }
        }
        xhr.open("POST", url, true);
        xhr.setRequestHeader("Content-Type", "application/octet-stream");
        
        $.ajax({url:options.qnToken, dataType: "json",success:function(token){
        	xhr.setRequestHeader("Authorization", "UpToken "+token.uptoken);
        	qiniuUrl = token.qiniuUrl;
            xhr.send(pic);
        }})
        
    }
    
    var uploadHtml = function(obj, opt){
    	$(obj).html('');
    	var id = $(obj).attr("id");
    	
    	var dataType = '';
    	if(opt.type == '' || opt.type.indexOf("image") != -1){
    		dataType += opt.image;
    	}
    	if(opt.type == '' || opt.type.indexOf("video") != -1){
    		dataType += opt.video;
    	}
    	
    	var multipleStr = '';
    	if(opt.multiple){
    		multipleStr = 'multiple="true"';
    	}
    	
    	var upload = $('<div class="upload">'+
			'<div class="upload-add" style="width:'+opt.width+'px;height:'+opt.height+'px;">'+
				'<i class="upload-icon"></i>'+
			'</div>'+
			'<input type="file" id="file_'+id+'" '+multipleStr+' accept="'+dataType+'" style="display: none;"/>'+
		'</div>');
    	
    	if(opt.data != null){
    		$.each(opt.data, function(i,v){
    			if(v.url != null){
    				var img = addFile(id, upload, v.url, opt);
        			if(v.checked && (opt.choose == 'check' || opt.choose == 'radio')){
        				img.find(".upload-choose").show();
        			}
        			if(v.text != null){
        				img.find(".upload-textaea").html(v.text);
        			}
        			addFileInput(img);
        			img.find("input[name='"+id+"']").val(v.url);
    			}
    		});
    	}
    	
    	
    	upload.find(".upload-add").click(function(){
    		upload.find("input[type='file']").click();
    	});
    	upload.find("input[type='file']").change(function(e) {
			var files = e.target.files;
			if(window.FileReader){
				$.each(files, function(i,file){
					var reader = new FileReader();
					reader.readAsDataURL(file);
					reader.onload = function(evt){
						var fext = (file.name.split(".").length >0?file.name.split(".")[file.name.split(".").length-1]:'')
						if(fext == 'mp4'){
							var video = $('<video src="'+URL.createObjectURL(file)+'" controls></video>');
							video[0].onloadedmetadata = function () {
								var width = this.videoWidth;
								var height = this.videoHeight;
								var fileNme = new Date().getTime() +"_wh"+width+"x"+height+"."+fext;
								var img = addFile(id, upload, URL.createObjectURL(file), opt, 'video');
								var load = $('<div style="position: absolute;"><div class="upload-loadbox"></div><div class="upload-load"></div><div class="upload-text">上传中...</div></div>');
								img.find(".upload-img").before(load);
								if(opt.qn){
									putb64(evt.target.result, file.size, fileNme, function(path){
										img.find(".upload-img").attr("src",path+"?vframe/jpg/offset/2/w/"+width	+"/h/"+height);
										img.find("input[data='"+id+"']").val(path);
										load.remove();
										addFileInput(img);
									});
								}else {
									$.ajax({url:opt.uploadUrl, type:"post", data:{baseDateURL: evt.target.result, name:fileNme}, success:function(ret){
										if(ret.success){
											img.find(".upload-img").attr("src",ret.obj.path+"?vframe/jpg/offset/2/w/"+width	+"/h/"+height);
											img.find("input[data='"+id+"']").val(ret.obj.path);
											load.remove();
											addFileInput(img);
										}
									}});
								}
								
							};
						} else{
							var image = new Image();  
							image.src = URL.createObjectURL(file);
							image.onload = function(){
								var width = image.width;
								var height = image.height;
								var fileNme = new Date().getTime() +"_wh"+width+"x"+height+"."+fext;
								var img = addFile(id, upload, URL.createObjectURL(file), opt, 'image');
								var load = $('<div style="position: absolute;"><div class="upload-loadbox" style="width:'+(opt.width-2)+'px;height:'+(opt.height-2)+'px"></div><div class="upload-load" style="margin:'+(opt.height/2-12)+'px '+(opt.width/2-12)+'px"></div><div class="upload-text" style="margin:'+(opt.height/2+15)+'px 0px 0px '+(opt.width/2-28)+'px">上传中...</div></div>');
								img.find(".upload-img").before(load);
								
								if(opt.qn){
									putb64(evt.target.result, file.size, fileNme, function(path){
										img.find(".upload-img").attr("src", path);
										img.find("input[data='"+id+"']").val(path);
										load.remove();
										addFileInput(img);
									});
								} else {
									$.ajax({url:opt.uploadUrl, type:"post", data:{baseDateURL: evt.target.result, name:fileNme}, success:function(ret){
										if(ret.success){
											img.find(".upload-img").attr("src", ret.obj.path);
											img.find("input[data='"+id+"']").val(ret.obj.path);
											load.remove();
											addFileInput(img);
										}
									}});
								}
							};
						}
					}
				});
			}else{
				console.log('浏览器不支持FileReader');
			}
            
        });
    	
    	$(obj).append(upload);
    }
    
    var uploadFile=function(obj, opt){
    	uploadHtml(obj, opt);
    	
    }
    var success=function(obj, ret){
    	
    }
    var uploadGetData = function(obj){
    	var id = $(obj).attr("id");
    	var data = [];
    	$(obj).find(".upload-yd").each(function(i,v){
    		var d = {};
    		d.url = $(v).find("input[name='"+id+"']").val();
    		d.type = $(v).find("input[name='"+id+"Type']").val();
    		d.checked = $(v).find("input[name='"+id+"Checked']").val();
    		d.text = $(v).find("textarea[name='"+id+"Text']").val();
    		data.push(d);
    	});
    	return data;
    }

    
    //** 单图上传 **/
    var jjUploadClipFile = function(obj, opt){
    	$(obj).html('');
    	var id = $(obj).attr("id");
    	var upload = $('<div class="upload">'+
    			'<div class="upload-add" style="width:'+opt.width+'px;height:'+opt.height+'px;">'+
    				'<i class="upload-icon"></i>'+
    			'</div>'+
    			'<input type="file" id="file_'+id+'" multiple="true" accept="'+opt.image+'" style="display: none;"/>'+
    		'</div>');
    	
    	if(opt.url != null){
    		upload.find(".upload-add").hide();
    		var img = addFile(id, upload, opt.url, opt);
    		if(opt.text != null){
    			img.find(".upload-textaea").html(opt.text);
    		}
    		addFileInput(img);
    		img.find("input[name='"+id+"']").val(opt.url);
    	}
    	
    	$(obj).append(upload);
    	
    	
    	
    	upload.find(".upload-add").click(function(){
    		if(opt.isClip){
        		clipImg(upload, opt, obj);
        		upload.find("input[type='file']").click();
        	} else {
        		upload.find("input[type='file']").click();
        	}
    	});
    	
    	if(opt.isClip){
    		return
    	}
    	
    	upload.find("input[type='file']").change(function(e) {
			var files = e.target.files;
			if(window.FileReader){
				$.each(files, function(i,file){
					var reader = new FileReader();
					reader.readAsDataURL(file);
					reader.onload = function(evt){
						var fext = (file.name.split(".").length >0?file.name.split(".")[file.name.split(".").length-1]:'')
						if(fext == 'mp4'){
						} else{
							var image = new Image();  
							image.src = URL.createObjectURL(file);
							image.onload = function(){
								var width = image.width;
								var height = image.height;
								var fileNme = new Date().getTime() +"_wh"+width+"x"+height+"."+fext;
								upload.find(".upload-add").hide();
								var img = addFile(id, upload, URL.createObjectURL(file), opt, 'image');
								var load = $('<div style="position: absolute;"><div class="upload-loadbox" style="width:'+(opt.width-2)+'px;height:'+(opt.height-2)+'px"></div><div class="upload-load" style="margin:'+(opt.height/2-12)+'px '+(opt.width/2-12)+'px"></div><div class="upload-text" style="margin:'+(opt.height/2+15)+'px 0px 0px '+(opt.width/2-28)+'px">上传中...</div></div>');
								img.find(".upload-img").before(load);
								if(opt.qn){
									putb64(evt.target.result, file.size, fileNme, function(path){
										img.find(".upload-img").attr("src", path);
										img.find("input[data='"+id+"']").val(path);
										load.remove();
										addFileInput(img);
									});
								} else {
									$.ajax({url:opt.uploadUrl, type:"post", data:{baseDateURL: evt.target.result, name:fileNme}, success:function(ret){
										if(ret.success){
											img.find(".upload-img").attr("src", ret.obj.path);
											img.find("input[data='"+id+"']").val(ret.obj.path);
											load.remove();
											addFileInput(img);
										}
									}});
								}
							};
						}
					}
				});
			}else{
				console.log('浏览器不支持FileReader');
			}
            
        });
    	
    	
    }
    //** 单图上传 **/
    
    
    var clipImg = function(upload, opt, obj){
    	var id = $(obj).attr("id");
    	
    	var html = '<div class="clip-block"><div class="clip-mask"></div>'+
        	'<div class="clip">'+
        		
        		'<div id="clip_'+id+'" class="clip-area" style="width:200px;height:200px"></div>'+
    			'<div class="clip-group">'+
//    				'<span class="clip-group-btn">原图</span>'+
    				'<span class="clip-group-btn clip-upload">上传</span>'+
    				'<span id="clip_ok_'+id+'" class="clip-group-btn">截取</span>'+
    			'</div>'+
    			'<span class="clip-close">×</span>'+
        	'</div></div>';
    	var clipObj = $(html);
    	$("body").append(clipObj);
    	
    	clipObj.find(".clip-upload").click(function(){
    		$("#file_"+id).click();
    	});
    	
    	clipObj.find(".clip-close").click(function(){
    		clipObj.remove();
    	});
    	var width = 200;
    	if(opt.width > opt.height){
    		width = 200;
    		height = width/opt.width*opt.height;
    	} else {
    		height = 200;
    		width = height/opt.height*opt.width;
    	}
    	
    	var clipArea = new bjj.PhotoClip("#clip_"+id, {
  			size: [width, height],
  			outputSize: [opt.width*2, opt.height*2],
  			file: "#file_"+id,
  			ok: "#clip_ok_"+id,
  			loadStart: function() {
  				console.log("照片读取中");
  			},
  			loadComplete: function() {
  				console.log("照片读取完成");
  			},
  			clipFinish: function(dataURL) {
  				var width = opt.width;
				var height = opt.height;
				var fileNme = new Date().getTime() +"_wh"+width+"x"+height+".jpg";
				upload.find(".upload-add").hide();
  				var img = addFile(id, upload, dataURL, opt, 'image');
				var load = $('<div style="position: absolute;"><div class="upload-loadbox" style="width:'+(opt.width-2)+'px;height:'+(opt.height-2)+'px"></div><div class="upload-load" style="margin:'+(opt.height/2-12)+'px '+(opt.width/2-12)+'px"></div><div class="upload-text" style="margin:'+(opt.height/2+15)+'px 0px 0px '+(opt.width/2-28)+'px">上传中...</div></div>');
				img.find(".upload-img").before(load);
  				if(opt.qn){
  					var arr = dataURL.split(','), mime = arr[0].match(/:(.*?);/)[1],
	  			        bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
	  			    while(n--){
	  			        u8arr[n] = bstr.charCodeAt(n);
	  			    }
	  			    var b = new Blob([u8arr], {type:mime});
					putb64(dataURL, b.size, fileNme, function(path){
						img.find(".upload-img").attr("src", path);
						img.find("input[data='"+id+"']").val(path);
						load.remove();
						addFileInput(img);
					});
				} else {
					$.ajax({url:opt.uploadUrl, type:"post", data:{baseDateURL: dataURL, name:fileNme}, success:function(ret){
						if(ret.success){
							img.find(".upload-img").attr("src", ret.obj.path);
							img.find("input[data='"+id+"']").val(ret.obj.path);
							load.remove();
							addFileInput(img);
						}
					}});
				}
  				clipObj.remove();
  			}
  		});
    	
    	
    }
    
    $.extend({
        jjInitUpload:function(opt) {
        	var opt2 = $.extend({}, options, opt||{});
        	initUpload(opt2);
        }
    });
    $.fn.extend({
    	jjUploadFile:function(opt){
    		 var opt2 = $.extend({}, options, opt||{});
             this.each(function(){
            	 uploadFile(this, opt2);
             });
    	},
    	jjUploadClipFile:function(opt){
      		 var opt2 = $.extend({}, options, opt||{});
               this.each(function(){
               	jjUploadClipFile(this, opt2);
               });
       	},
    	jjUploadGetData:function(opt){
    		return uploadGetData(this);
    	}
    });
})(jQuery);